import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/darkweb/widget/shrink_wrap.dart';
import 'package:tiktokadult/hj_utils/history_record_util.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

final searchHistortyProvider = SearchHistoryProvider();
const maxSearchHistoryNum = 10;

class SearchHistoryProvider {
  final histories = <String>[].obs;

  fetchSearchHistory() async {
    histories.clear();
    histories.addAll(await HistoryRecordUtil.getSearchHistorys()); //
    // notifyListeners();
  }

  saveHistories(String text) {
    // //如果超出最大個數
    if (histories.length >= maxSearchHistoryNum) {
      histories.removeLast();
    }
    if (histories.contains(text)) {
      histories.remove(text);
    }
    histories.insert(0, text);
    HistoryRecordUtil.saveSearch(histories);
    // notifyListeners();
  }

  onDeleteOneHistory(String key) {
    histories.deleteSingleHistory(key);
    // notifyListeners();
  }

  onDeleteAllHistory() async {
    await HistoryRecordUtil.saveSearch([]);
    histories.clear();
    // notifyListeners();
  }
}

class SearchHistoryView extends StatefulWidget {
  const SearchHistoryView({super.key, required this.onHistoryClick});

  final Function(String keyword) onHistoryClick;

  @override
  State<SearchHistoryView> createState() => _SearchHistoryViewState();
}

class _SearchHistoryViewState extends State<SearchHistoryView> {
  bool isExpandData = false;

  int get itemCount {
    return searchHistortyProvider.histories.length;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      searchHistortyProvider.fetchSearchHistory();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (searchHistortyProvider.histories.isEmpty) return SizedBox.shrink();
      return Container(
        padding: EdgeInsets.only(left: 12, right: 12, top: 12),
        width: Get.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  '搜索记录',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Spacer(),
                InkWell(
                  onTap: () {
                    searchHistortyProvider.onDeleteAllHistory();
                  },
                  child: Container(
                    padding: EdgeInsets.all(1),
                    child: Text(
                      '清除全部记录',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.9),
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            12.sizeBoxH,
            GridView.builder(
              padding: EdgeInsets.zero,
              itemCount: itemCount,
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                childAspectRatio: 79 / 34,
                mainAxisSpacing: 12,
                crossAxisSpacing: 12,
              ),
              itemBuilder: (context, index) {
                final tag = searchHistortyProvider.histories[index];
                return GestureDetector(
                  onTap: () => widget.onHistoryClick(tag),
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(3),
                    ),
                    child: Text(
                      tag,
                      maxLines: 1,
                      style: TextStyle(
                        color: Color(0xffFFFFFF),
                        fontSize: 12,
                      ),
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      );
    });
  }
}

extension _ on List<String> {
  deleteSingleHistory(String his) {
    if (this.contains(his)) {
      this.remove(his);
      // HistoryRecordUtil.saveSearch(this);
    }
  }
}
